package com.shuda.business.data.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shuda.business.data.dto.DataProcessingEngineDTO;
import com.shuda.business.data.dto.DataProcessingEngineQueryDTO;
import com.shuda.business.data.entity.DataProcessingEngineEntity;
import com.shuda.business.data.mapper.DataProcessingEngineMapper;
import com.shuda.business.data.service.DataProcessingEngineService;
import com.shuda.common.dto.PageDTO;
import com.shuda.common.dto.PageResult;
import com.shuda.common.exception.BusinessException;
import com.shuda.common.utils.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 数据处理引擎服务实现类
 */
@Service
public class DataProcessingEngineServiceImpl extends ServiceImpl<DataProcessingEngineMapper, DataProcessingEngineEntity> 
        implements DataProcessingEngineService {

    @Autowired
    private DataProcessingEngineMapper dataProcessingEngineMapper;

    @Override
    public Boolean collisionCheck(Long dataId) {
        // 模拟撞库检测逻辑
        // 实际实现中需要查询数据库检查是否已存在相同数据
        return false; // 默认返回false，表示没有撞库
    }

    @Override
    public Boolean processData(Long dataId) {
        // 模拟进件处理逻辑
        // 实际实现中需要调用数据处理流程
        return true; // 默认返回true，表示处理成功
    }

    @Override
    public PageResult<DataProcessingEngineDTO> getFieldMappingPage(PageDTO pageDTO, DataProcessingEngineQueryDTO queryDTO) {
        Page<DataProcessingEngineEntity> page = new Page<>(pageDTO.getPageNum(), pageDTO.getPageSize());
        
        LambdaQueryWrapper<DataProcessingEngineEntity> wrapper = new LambdaQueryWrapper<>();
        
        if (queryDTO.getChannelId() != null) {
            wrapper.eq(DataProcessingEngineEntity::getChannelId, queryDTO.getChannelId());
        }
        
        if (StringUtils.hasText(queryDTO.getConfigType())) {
            wrapper.eq(DataProcessingEngineEntity::getConfigType, queryDTO.getConfigType());
        }
        
        if (StringUtils.hasText(queryDTO.getSourceField())) {
            wrapper.like(DataProcessingEngineEntity::getSourceField, queryDTO.getSourceField());
        }
        
        if (StringUtils.hasText(queryDTO.getTargetField())) {
            wrapper.like(DataProcessingEngineEntity::getTargetField, queryDTO.getTargetField());
        }
        
        if (StringUtils.hasText(queryDTO.getConfigStatus())) {
            wrapper.eq(DataProcessingEngineEntity::getConfigStatus, queryDTO.getConfigStatus());
        }
        
        if (queryDTO.getStartTime() != null) {
            wrapper.ge(DataProcessingEngineEntity::getCreateTime, queryDTO.getStartTime());
        }
        
        if (queryDTO.getEndTime() != null) {
            wrapper.le(DataProcessingEngineEntity::getCreateTime, queryDTO.getEndTime());
        }
        
        wrapper.orderByDesc(DataProcessingEngineEntity::getCreateTime);
        
        IPage<DataProcessingEngineEntity> result = dataProcessingEngineMapper.selectPage(page, wrapper);
        
        List<DataProcessingEngineDTO> dtoList = result.getRecords().stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
        
        return new PageResult<>(dtoList, result.getTotal(), result.getCurrent(), result.getSize());
    }

    @Override
    public DataProcessingEngineDTO getFieldMappingById(Long id) {
        DataProcessingEngineEntity entity = dataProcessingEngineMapper.selectById(id);
        if (entity == null) {
            throw new BusinessException("字段映射配置不存在");
        }
        return convertToDTO(entity);
    }

    @Override
    public Long createFieldMapping(DataProcessingEngineDTO dto) {
        DataProcessingEngineEntity entity = convertToEntity(dto);
        entity.setConfigType("field_mapping");
        entity.setConfigStatus("enabled");
        entity.setCreateBy(SecurityUtils.getCurrentUsername());
        entity.setCreateTime(LocalDateTime.now());
        entity.setUpdateBy(SecurityUtils.getCurrentUsername());
        entity.setUpdateTime(LocalDateTime.now());
        entity.setDeleted(0);
        
        dataProcessingEngineMapper.insert(entity);
        return entity.getId();
    }

    @Override
    public void updateFieldMapping(Long id, DataProcessingEngineDTO dto) {
        DataProcessingEngineEntity existingEntity = dataProcessingEngineMapper.selectById(id);
        if (existingEntity == null) {
            throw new BusinessException("字段映射配置不存在");
        }
        
        DataProcessingEngineEntity entity = convertToEntity(dto);
        entity.setId(id);
        entity.setUpdateBy(SecurityUtils.getCurrentUsername());
        entity.setUpdateTime(LocalDateTime.now());
        
        dataProcessingEngineMapper.updateById(entity);
    }

    @Override
    public void deleteFieldMapping(Long id) {
        DataProcessingEngineEntity entity = dataProcessingEngineMapper.selectById(id);
        if (entity == null) {
            throw new BusinessException("字段映射配置不存在");
        }
        
        entity.setDeleted(1);
        entity.setUpdateBy(SecurityUtils.getCurrentUsername());
        entity.setUpdateTime(LocalDateTime.now());
        dataProcessingEngineMapper.updateById(entity);
    }

    @Override
    public String getScriptConfig(Long channelId) {
        LambdaQueryWrapper<DataProcessingEngineEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DataProcessingEngineEntity::getChannelId, channelId)
                .eq(DataProcessingEngineEntity::getConfigType, "script")
                .eq(DataProcessingEngineEntity::getDeleted, 0)
                .orderByDesc(DataProcessingEngineEntity::getCreateTime)
                .last("LIMIT 1");
        
        DataProcessingEngineEntity entity = dataProcessingEngineMapper.selectOne(wrapper);
        return entity != null ? entity.getTransformScript() : "";
    }

    @Override
    public void saveScriptConfig(Long channelId, String scriptConfig) {
        // 先查询是否已存在脚本配置
        LambdaQueryWrapper<DataProcessingEngineEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DataProcessingEngineEntity::getChannelId, channelId)
                .eq(DataProcessingEngineEntity::getConfigType, "script")
                .eq(DataProcessingEngineEntity::getDeleted, 0)
                .orderByDesc(DataProcessingEngineEntity::getCreateTime)
                .last("LIMIT 1");
        
        DataProcessingEngineEntity existingEntity = dataProcessingEngineMapper.selectOne(wrapper);
        
        if (existingEntity != null) {
            // 更新现有配置
            existingEntity.setTransformScript(scriptConfig);
            existingEntity.setUpdateBy(SecurityUtils.getCurrentUsername());
            existingEntity.setUpdateTime(LocalDateTime.now());
            dataProcessingEngineMapper.updateById(existingEntity);
        } else {
            // 创建新配置
            DataProcessingEngineEntity entity = new DataProcessingEngineEntity();
            entity.setChannelId(channelId);
            entity.setConfigType("script");
            entity.setTransformScript(scriptConfig);
            entity.setScriptLanguage("javascript"); // 默认使用JavaScript
            entity.setConfigStatus("enabled");
            entity.setCreateBy(SecurityUtils.getCurrentUsername());
            entity.setCreateTime(LocalDateTime.now());
            entity.setUpdateBy(SecurityUtils.getCurrentUsername());
            entity.setUpdateTime(LocalDateTime.now());
            entity.setDeleted(0);
            
            dataProcessingEngineMapper.insert(entity);
        }
    }

    private DataProcessingEngineDTO convertToDTO(DataProcessingEngineEntity entity) {
        DataProcessingEngineDTO dto = new DataProcessingEngineDTO();
        BeanUtils.copyProperties(entity, dto);
        return dto;
    }

    private DataProcessingEngineEntity convertToEntity(DataProcessingEngineDTO dto) {
        DataProcessingEngineEntity entity = new DataProcessingEngineEntity();
        BeanUtils.copyProperties(dto, entity);
        return entity;
    }
}